

import nw from "nw-lafjs";

import {fail, ok} from "@/utils/responseUtil";
import {encrypt} from "@/utils/passwordUtil";
import * as process from "process";
import cloud from "@lafjs/cloud";
const db = cloud.database()
const _ = db.command
// @ts-ignore
export default async function (ctx: FunctionContext) {
  /**
   * {
   *   "username": "wuzuxian",
   *   "password": "wzxwsq1314",
   *   "name": "吴祖贤",
   *   "phone": "18720701353"
   * }
   */
  let body  = ctx.body
  //校验参数
  if (nw.util.isNull(body.username)){
      return fail("用户名不能为空")
  }
  if (nw.util.isNull(body.password)){
    return fail("密码不能为空")
  }
  if (nw.util.isNull(body.name)){
    return fail("昵称不能为空")
  }
  //2.校验username和phone是否唯一
  let userNameCount = await nw.db.count({
    dbName:"admin",
    whereJson:{
      deleted:0,
      username:body.username
    }
  });
  console.log(`userNameCount=${userNameCount}`)
  if (userNameCount>0){
    return fail("用户名重复")
  }
  let phoneCount = await nw.db.count({
    dbName:"admin",
    whereJson:{
      deleted:0,
      phone:_.eq(body.phone)
    }
  });
  console.log(`phoneCount=${phoneCount}`)
  if (phoneCount>0){
    return fail("电话重复")
  }

  //3.组装成功的数据结构
  let user = {
    username: body.username,
    password: encrypt(body.password,process.env.SALT),
    name: body.name,
    phone: body.phone,
    wareId:0,
    createTime:new Date(),
    updateTime:new Date(),
    deleted:0
  }
  //4.保存数据结构即可
  let result = await nw.db.add({
    dbName:"admin",
    dataJson:user,
    cancelAddTime : true
  });

  if (nw.util.isNull(result)){
    return fail("注册失败")
  }

  // @ts-ignore
  user._id = result
  return ok(user,"注册成功")
}
